package cwiczenia;

import jwt.lab02.Utils;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Korzysta z Lab02 - JavaMail
 */

public class InboxServlet extends HttpServlet {

    String popServer, popUser, popPass;


    public void init() throws ServletException {
        popServer = getInitParameter("popServer");
        popUser = getInitParameter("popUser");
        popPass = getInitParameter("popPass");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf8");
        if (request.getParameter("i") != null) {
            PrintWriter pw = response.getWriter();
            pw.println("<html><body><h1>Jakis list:</h1>");

            try {
                pw.print(messageToHTML(Utils.getAllMessages(popServer, popUser, popPass), new Integer(request.getParameter("i"))));
            } catch (MessagingException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }

            pw.close();
        } else {
            PrintWriter pw = response.getWriter();
            pw.println("<html><body><h1>Twoja skrzynka pocztowa:</h1>");

            try {
                pw.print(messagesToHTML(Utils.getAllMessages(popServer, popUser, popPass)));
            } catch (MessagingException e) {
                e.printStackTrace();
            }

            pw.println("</body></html>");
            pw.close();
        }
    }

    private String messageToHTML(Message[] messages, Integer i) throws MessagingException, IOException {
        StringBuffer sb = new StringBuffer();

        sb.append("<h3>" + Utils.messageToString(messages[i]) + "</h3>");
        sb.append(messages[i].getContent());

        return sb.toString();
    }

    public static String messagesToHTML(Message[] messages) throws MessagingException {
        StringBuffer sb = new StringBuffer();

        sb.append("<ul>");

        for (int i = 0; i < messages.length; i++)
            sb.append("<li><a href=\"Inbox?i=" + i + "\">" + Utils.messageToString(messages[i]) + "</a></li>");

        sb.append("</ul>");

        return sb.toString();
    }
}
